package Beans;

import BO.Service;
import ws.UserUI;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;

public class SearchUserBean implements Serializable {

    private String search;
    private List<UserUI> data = new ArrayList<UserUI>();
    private UserUI selected;

    public SearchUserBean() {
    }

    public List<UserUI> getData() {
        if (search != null && search.length() >= 2) {
            data = Service.searchAfterUser(search);
        }
        return data;
    }

    public void setData(List<UserUI> data) {
        this.data = data;
    }

    public String getSearch() {
        return search;
    }

    public void setSearch(String search) {
        this.search = search;
    }

    public UserUI getSelected() {
        return selected;
    }

    public void setSelected(UserUI selected) {
        this.selected = selected;
    }

    public void friendListener(ActionEvent event){
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        UserUI user = (UserUI)session.getAttribute("User");
        Service.addFriendship(user.getId(),((UserUI) event.getComponent().getAttributes().get("selection")).getId());
    }
    
    public void selectionListener(ActionEvent event) {
        this.selected = (UserUI) event.getComponent().getAttributes().get("selection");
        FacesContext context = FacesContext.getCurrentInstance();
        //TODO: tänk över design - skicka parameter till vyn eller sätt variabeln genom vyn istället för detta?
        viewUserBean viewUserBean = (viewUserBean) context.getApplication().evaluateExpressionGet(context, "#{viewUserBean}", viewUserBean.class);
        viewUserBean.setSelected(selected);
    }

    public String goToDetails() {
        return "true";
    }
}
